package com.aoip.telemetry.telemetry.configureui.business.storage.merge.service.impl;

import com.aoip.telemetry.telemetry.configureui.business.storage.merge.mapper.DataMergeMapper;
import com.aoip.telemetry.telemetry.configureui.business.storage.merge.service.DataMergeService;
import com.aoip.telemetry.telemetry.core.redis.RedisCache;
import com.aoip.telemetry.telemetry.entity.common.MergeTableDataEntity;
import com.aoip.telemetry.telemetry.entity.enums.CacheKeyEnum;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @author chenbai
 * @version 1.0
 * @date 2022/4/19 20:17
 */
@Service
@DS("telemetry")
public class DataMergeServiceImpl implements DataMergeService {
    @Resource
    private DataMergeMapper mapper;
    @Resource
    private RedisCache redisCache;

    @Override
    public List<MergeTableDataEntity> list(MergeTableDataEntity entity) {
        QueryWrapper<MergeTableDataEntity> queryWrapper = new QueryWrapper<>();
        return mapper.selectList(queryWrapper);
    }

    @Override
    public MergeTableDataEntity detail(String id) {
        return mapper.selectById(id);
    }

    @Override
    public int insert(MergeTableDataEntity entity) {
        redisCache.setCacheObject(CacheKeyEnum.MERGE_DATA + ":" + entity.getId(), entity);
        return mapper.insert(entity);
    }

    @Override
    public int update(MergeTableDataEntity entity) {
        redisCache.setCacheObject(CacheKeyEnum.MERGE_DATA + ":" + entity.getId(), entity);
        return mapper.updateById(entity);
    }

    @Override
    public int initCache() {
        List<MergeTableDataEntity> list = list(new MergeTableDataEntity());
        Collection<String> keys = redisCache.keys(CacheKeyEnum.MERGE_DATA + ":*");
        redisCache.deleteObject(keys);
        list.forEach(item -> redisCache.setCacheObject(CacheKeyEnum.MERGE_DATA + ":" + item.getId(), item));
        return list.size();
    }

    @Override
    public void delete(String[] ids) {
        mapper.deleteBatchIds(Arrays.asList(ids));
    }
}
